package bupt.com.test;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.unionman.jazzlib.SystemProperties;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bupt.com.test.api.LoadInterface;
import bupt.com.test.bean.BaseInfo;
import bupt.com.test.bean.BaseResult;
import bupt.com.test.bean.FirstResult;
import bupt.com.test.bean.MainResult;
import bupt.com.test.bean.ProgramInfo;
import bupt.com.test.bean.RequestInfo;
import bupt.com.test.center.LoadCenter;
import bupt.com.test.config.Constant;
import bupt.com.test.config.FileCallback;
import bupt.com.test.config.RetrofitModule;
import bupt.com.test.util.HardwareUtils;
import bupt.com.test.widget.CropEndImageView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";

    private CropEndImageView bivImg;

    private Gson gson;

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.show_text);
//        test();
        gson = new Gson();

        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                pickPhoto();
                String deviveId = getDeviveId();
                Log.d(TAG, "deviveId: " + deviveId);
                Toast.makeText(MainActivity.this, "" + deviveId, Toast.LENGTH_LONG).show();
            }
        });
        RequestInfo info = new RequestInfo();
        RequestInfo.ParamsBean bean = new RequestInfo.ParamsBean();
        bean.setAge("22");
        bean.setName("1233213");
        info.setParams(bean);
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        info.setPage(list);
        Log.d(TAG, "onCreate: ============");
        Call<JsonElement> jsonElementCall = LoadCenter.getInstance().get("http://182.18.26.5:8082/CollectionServer/Sync");
        jsonElementCall.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                Log.d(TAG, "onResponse: " + response.code());
                if (response.code() == 200) {
                    Log.d(TAG, "onResponse: " + response.body().toString());
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
            }
        });
        LoadCenter.getInstance().testData("http://182.18.26.5:8082/CollectionServer/Sync", "0101|1010|09;20160630131911;3032000015370004199;;com.guoantvbox.cs.launcher;应用111;20160630131911;<?>", new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "onResponse: " + response.code());
                if (response.code() == 200) {
                    Log.d(TAG, "onResponse: " + response.body().toString());
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
            }
        });
//
//        getFirstVideo();
//            getChannelInfo();
//        getChannelInfo();
//        bivImg = (CropEndImageView) findViewById(R.id.show_image);
//        bivImg.setDrawableOverlay(false);
//        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File
//                .separator,
//                "123.png");
//        getFirstVideo();
//        getProgramByFirstVideoId();
//        getProgramEpisodesNumberByProgramId();
//        getProgramByProgramIdFirst();
//        getProgramByProgramIdAndEpisodesNumber();
//        if (file.exists()) {
//            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//            bivImg.setImageBitmap(bitmap);
//            Log.d(TAG, "onCreate: ===========");
//            return;
//        }
//        loadImage();

    }

    /**
     * 获取手机设备id
     *
     * @return
     */
    public String getDeviveId() {
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telManager.getDeviceId();
        return deviceId;
    }

    private void getChannelInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", "1");
        LoadCenter.getInstance().load(Constant.getChannelInfoByPage, map, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "onResponse: " + response.body().toString());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }

    private void test() {
        //        String content = "120160803.txt";
//        textView.append(content.substring(0,9));
        Log.d(TAG, "onCreate: $$$$$$$$$$$$$$$$ ip = " + HardwareUtils.getAndroidIp(MainActivity.this, 0));
        Log.d(TAG, "onCreate: $$$$$$$$$$$$$$$$ androidcode = " + HardwareUtils.getAndroidCode());
        Log.d(TAG, "onCreate: $$$$$$$$$$$$$$$$ szie = " + HardwareUtils.getTotalMemory(MainActivity.this));
        Log.d(TAG, "onCreate: $$$$$$$$$$$$$$$$ yingjian = " + HardwareUtils.getPhoneInfo(MainActivity.this));
        textView.append("ip = " + HardwareUtils.getAndroidIp(MainActivity.this, 0));
        textView.append("\nandroid版本 = " + HardwareUtils.getAndroidCode());
        textView.append("\n大小 = " + HardwareUtils.getTotalMemory(MainActivity.this));
        textView.append("\n硬件型号 = " + HardwareUtils.getPhoneInfo(MainActivity.this));
        textView.append("\n硬件版本 = " + SystemProperties.get("ro.build.hardware.id"));
        String[] split = SystemProperties.get("ro.build.version.incremental").split("\\.");
        Log.d(TAG, "onCreate:length " + split.length);
        String s1 = split[split.length - 2];
        Log.d(TAG, "onCreate: " + s1);
        textView.append("\n软件版本 = " + s1.substring(2));
        textView.append("\n区域 = " + SystemProperties.get("persist.sys.areacode"));

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        String runningPackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();

        textView.append("\n顶层应用的包名：" + runningPackageName);

        //获得系统运行的进程
        List<ActivityManager.RunningAppProcessInfo> appList1 = mActivityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo running : appList1) {
            if (running == null) {
                return;
            }
            System.out.println(running.processName);
            textView.append("\n系统运行的进程: id = " + running.pid + ",name = " + running.processName);
        }
        System.out.println("================");

        //获得当前正在运行的service
        List<ActivityManager.RunningServiceInfo> appList2 = mActivityManager
                .getRunningServices(100);
        for (ActivityManager.RunningServiceInfo running : appList2) {
            if (running == null) {
                return;
            }
            System.out.println(running.service.getClassName());
            textView.append("\n当前正在运行的service:id = " + running.pid + ",name = " + running.service.getClassName());
        }

        System.out.println("================");

        //获得当前正在运行的activity
        List<ActivityManager.RunningTaskInfo> appList3 = mActivityManager
                .getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo running : appList3) {
            if (running == null) {
                return;
            }
            System.out.println(running.baseActivity.getClassName());
            textView.append("\n当前正在运行的activity :PackageName = " + running.baseActivity.getPackageName() + ",name = " + running.baseActivity.getClassName());
        }
        System.out.println("================");

        //获得最近运行的应用
//        List<ActivityManager.RecentTaskInfo> appList4 = mActivityManager
//                .getRecentTasks(20, 0);
//        System.out.println(appList4.size() + "");
//        for (ActivityManager.RecentTaskInfo running : appList4) {
//            System.out.println(running.origActivity.getClassName());
//            textView.append("\n最近运行的应用 : PackageName" + running.origActivity.getPackageName() + ",name = " + running.origActivity.getClassName());
//        }
    }

    private void getProgramByProgramIdAndEpisodesNumber() {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", "GUANGSHI\\26119");
        map.put("episodesNumber", 25);
        LoadCenter.getInstance().load(Constant.getProgramByProgramIdAndEpisodesNumber, map, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "onResponse: " + response.body().toString());
                BaseInfo info = (BaseInfo) Constant.parseData(response.body().toString(), gson, new TypeToken<BaseInfo>() {
                });
                Log.d(TAG, "onResponse------info-----: " + info.toString());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }

    private void getProgramByProgramIdFirst() {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", "GUANGSHI\\26119");
        map.put("orderType", 1);
        LoadCenter.getInstance().load(Constant.getProgramByProgramIdFirst, map, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "onResponse: " + response.body().toString());
                ProgramInfo programInfo = (ProgramInfo) Constant.parseData(response.body().toString(), gson, new TypeToken<ProgramInfo>() {
                });
                Log.d(TAG, "onResponse:------ProgramInfo------ " + programInfo.getContentInfo());
                Log.d(TAG, "onResponse:-----ProgramInfo------- " + programInfo.getDestPath());
                Log.d(TAG, "onResponse:------ProgramInfo------ " + programInfo.getProgramName());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                Log.v("MyKeyDown", "onkeydown=left");
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                Log.v("MyKeyDown", "onkeydown=up");
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Log.v("MyKeyDown", "onkeydown=right");
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                Log.v("MyKeyDown", "onkeydown=down");
                break;
            case KeyEvent.KEYCODE_DPAD_CENTER:
                Log.v("MyKeyDown", "onkeydown=center");
                break;
            case KeyEvent.KEYCODE_BACK:
                Log.v("MyKeyDown", "onkeydown=back");
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getProgramEpisodesNumberByProgramId() {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", "GUANGSHI\\26119");
        LoadCenter.getInstance().load(Constant.getProgramEpisodesNumberByProgramId, map, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                System.out.println(response.body().toString());
                Log.d(TAG, "onResponse: " + response.body().toString());
                List<Integer> list = (List<Integer>) Constant.parseData(response.body().toString(), gson, new TypeToken<List<Integer>>() {
                });
                Log.d(TAG, "onResponse: ------------" + list.toString());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }

    private void loadImage() {
        Call<ResponseBody> download = LoadCenter.getInstance().download("http://182.18.31.162:21580/poster/help.png", new FileCallback(Environment.getExternalStorageDirectory().getAbsolutePath() + File
                .separator,
                "123.png") {
            @Override
            public void onSuccess(File file) {
                Log.d(TAG, "onSuccess: ");
//                bivImg.setImage(file.getAbsolutePath());
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                bivImg.setImageBitmap(bitmap);
            }

            @Override
            public void disConnect() {
                Log.d(TAG, "disConnect: ");
            }

            @Override
            public void onProgress(long progress, long total) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }

    private void getFirstVideo() {
        Call<JsonElement> resBodyCall = LoadCenter.getInstance().get(Constant.getFirstVideo);
        resBodyCall.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                Log.d(TAG, "onResponse: =======" + response.body().toString());
                List<BaseResult> list = (List<BaseResult>) Constant.parseData(response.body().toString(), gson, new TypeToken<List<BaseResult>>() {
                });
                Log.d(TAG, "onResponse:!!!!!!!!!!1111 " + list.toString());
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Log.d(TAG, "onFailure: =======" + t.toString());
            }
        });
    }

    private void getProgramByFirstVideoId() {
        Map<String, Object> map = new HashMap<>();
        map.put("firstVideoId", "22");
        LoadCenter.getInstance().load(Constant.getProgramByFirstVideoId, map, new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "onResponse: &&&&&&&&&" + response.body().toString());
                FirstResult result = (FirstResult) Constant.parseData(response.body().toString(), gson, new TypeToken<FirstResult>() {
                });
                Log.d(TAG, "onResponse: " + result.toString());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure: &&&&&&&&&& " + t.toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        bivImg.release();
    }

    // 从相册选择
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String picturePath;
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                Log.d(TAG, "onActivityResult: " + uri);
                picturePath = getRealPathFromURI(uri);
                Log.d(TAG, "onActivityResult: " + picturePath);
                upLoade(picturePath);
            } else {
                Log.d(TAG, "onActivityResult: fail");
            }
        }
    }

    private void upLoade(String picturePath) {
        Map<String, RequestBody> params = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), "123456");
        params.put("appUserId", requestBody);
        File file = new File(picturePath);
        Log.d(TAG, "onCreate: -------------" + file.getAbsolutePath());
        Log.d(TAG, file.exists() + "");
        if (file.exists()) {
            Log.d(TAG, "onCreate: true");
            RequestBody imageRequestBody = RequestBody.create(MediaType.parse("image/*"), file);
            params.put("file" + "\";filename=\"" + file.getName() + "", imageRequestBody);
            Call<JsonElement> stringCall = RetrofitModule.getInstance().create(LoadInterface.class).upImage(Constant.updatePicture, params);
            stringCall.enqueue(new Callback<JsonElement>() {
                @Override
                public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                    Log.d(TAG, "onResponse: @@@@@@@" + response.body().toString());
                    MainResult result = (MainResult) Constant.parseData(response.body().toString(), gson, new TypeToken<MainResult>() {
                    });
                    Log.d(TAG, "onResponse: !!!!!!!!!!! " + result.toString());
                }

                @Override
                public void onFailure(Call<JsonElement> call, Throwable t) {
                    Log.d(TAG, "onFailure: @@@@@@@@@@@" + t.toString());
                }
            });
        } else {
            Log.d(TAG, "onCreate: false");
        }
    }

    // 获取相册图片
    private String getRealPathFromURI(Uri mUri) {
        if (mUri.getScheme().equals("file")) {
            return mUri.getPath();
        } else {
            String imgPath;
            Cursor cursor = getContentResolver().query(mUri, null, null, null,
                    null);
            cursor.moveToFirst();
            imgPath = cursor.getString(1);
            return imgPath;
        }
    }
}
